
<?php	
	
	require_once('../../lib/'.'BaseDir.inc.htm');		
	require_once (EIU_LIB.'View.class.htm');
	require_once(EIU_LIB.'DBCommon.class.htm');
	require_once (EIU_CLASS.'LoginClass.htm');
	
	@session_start(); 	
	
	$result = "";
	
	$oDB = new DBCommon();
	$conn =  $oDB->stl_openConn();
	
		
	$fromDate = $_POST["fromDate"];
	$toDate = $_POST["toDate"];
	
	if($fromDate == "") $fromDate = "1970-01-01";
	if($toDate == "") $toDate = date("Y-m-d");
	
		
	////////////// Tính chi phí ////////////	
	
	$condition = "`CostName` LIKE '%".$_POST['costName']."%' AND CreateDate >= '".$fromDate."' AND CreateDate <= '".$toDate."'";
		
	$qcostList = "
		SELECT 
			 `ID`,`CostName`,`Amount`,`CreateDate`,`LastUpdate`,`ModifiedBy`,`Remark`
		FROM `cost_tbl` 
		WHERE `isDeleted`=0 AND ".$condition." 
		ORDER BY `CostName` ";
	$result["cost"] = $oDB->stl_db_select($qcostList, $conn);
	
	//echo $qcostList;
	
	//Kết thúc tính chi phí
	
	///////////////Tồn đầu kỳ//////////////
	
	$q_ton = "
		SELECT A.`AssName`,A.`CATCode`,A.`Unit`, IFNULL(SumInputQuantity,0) AS SumInputQuantity,IFNULL(SumOutputQuantity,0) AS SumOutputQuantity,IFNULL(SumOutputAmount,0) AS SumOutputAmount,IFNULL(IFNULL(SumInputQuantity,0) - IFNULL(SumOutputQuantity,0),0) AS SumInStock
		FROM 
		(
				SELECT `asset_tbl`.`AssName`,`asset_tbl`.`CATCode`,SUM(`asset_tbl`.`Quantity`) AS SumInputQuantity,`asset_tbl`.`Unit`
				FROM `asset_tbl` RIGHT JOIN (
					SELECT RecvNoteCode, ReceiptDate
					FROM `recv_note_tbl` 
					WHERE recv_note_tbl.`isDeleted` = 0  AND `ReceiptDate` < '".$fromDate."' ORDER BY `RecvNoteCode` ASC  
				  ) AS recv ON asset_tbl.IOCode = recv.`RecvNoteCode`
				WHERE `asset_tbl`.`isDeleted` = 0 
				GROUP BY `asset_tbl`.`AssName`,`asset_tbl`.`Unit`,`asset_tbl`.`CATCode`
			) AS A 
			LEFT JOIN 
			(
			   SELECT `CATCode`,`AssName`,`Unit`,SUM(`Quantifty`) AS SumOutputQuantity,SUM(`Amount`) AS SumOutputAmount
				FROM `detail_io_tbl` RIGHT JOIN (
					SELECT `CostCode`,`DeliveryReceiptDate` 
					FROM `io_tbl` 
					WHERE `isDeleted` = 0  AND `DeliveryReceiptDate` < '".$fromDate."'
				) AS io ON `CostCode` = `IOCode`
				WHERE `isDeleted` = 0
				GROUP BY `CATCode`,`AssName`,`Unit`
			) AS B 	ON A.`AssName` = B.`AssName` AND A.`CATCode` = B.`CATCode` AND A.`Unit` = B.`Unit`
		ORDER BY A.`AssName` ASC
	";
	
	//echo $q_ton;
	
	$result["ton_dau_ky"] = $oDB->stl_db_select($q_ton, $conn);	
	
	///////////// Tính nhập trong kỳ /////////////////
	//	Nhập trong kỳ = tổng tất cả các phiếu nhập trong kỳ
	
	$asset_input = "
		SELECT AssID,AssName,CATCode,IOCode,Quantity,Unit,ReceiptDate,Price
		FROM asset_tbl RIGHT JOIN (
			SELECT RecvNoteCode, ReceiptDate
			FROM `recv_note_tbl` 
			WHERE recv_note_tbl.`isDeleted` = 0 AND `ReceiptDate` >= '".$fromDate."' AND `ReceiptDate` <= '".$toDate."' ORDER BY `RecvNoteCode` ASC  
		  ) AS recv ON asset_tbl.IOCode = recv.`RecvNoteCode`
			
		WHERE asset_tbl.isDeleted = 0		
		ORDER BY AssName ASC
	";
	//echo $asset_input;
	
	$result["input"] = $oDB->stl_db_select($asset_input, $conn);
	
	
	// Kết thúc tính nhập trong kỳ	
	
	///////////////Xuất trong kỳ//////////////
	$asset_output = "
		SELECT `IOCode`,`CATCode`,`AssCode`,`AssName`,`Quantifty`,`Price`,`Amount`,`Unit` ,`DeliveryReceiptDate` 
		FROM `detail_io_tbl` RIGHT JOIN (
			SELECT `CostCode`,`DeliveryReceiptDate` 
			FROM `io_tbl` 
			WHERE `isDeleted` = 0 AND `DeliveryReceiptDate` >= '".$fromDate."' AND `DeliveryReceiptDate` <= '".$toDate."'
		) AS io ON `CostCode` = `IOCode`
		
		WHERE `detail_io_tbl`.`isDeleted` = 0
		ORDER BY  IOCode ASC		
	";
	
	//echo $asset_output;
	
	$result["output"] = $oDB->stl_db_select($asset_output, $conn);		
	
	//Kết thúc xuất trong kỳ
	
	/**********XỬ LÝ DỮ LIỆU NHẬP XUẤT TỒN************/
	
	$arr_nhap_xuat_ton_report = "";
	$num_arr_ton_dau_ky = count($result["ton_dau_ky"]);
	for($i = 0; $i<$num_arr_ton_dau_ky; $i++)
	{
		
		$arr_nhap_xuat_ton_report[$result["ton_dau_ky"][$i]->{"AssName"}]["ton_dau_ky"] = $result["ton_dau_ky"][$i]->{"SumInStock"};
		$arr_nhap_xuat_ton_report[$result["ton_dau_ky"][$i]->{"AssName"}]["nhap_trong_ky"] = 0;
		$arr_nhap_xuat_ton_report[$result["ton_dau_ky"][$i]->{"AssName"}]["xuat_trong_ky"] = 0;
		$arr_nhap_xuat_ton_report[$result["ton_dau_ky"][$i]->{"AssName"}]["Unit"] = $result["ton_dau_ky"][$i]->{"Unit"};
		$arr_nhap_xuat_ton_report[$result["ton_dau_ky"][$i]->{"AssName"}]["CATCode"] = $result["ton_dau_ky"][$i]->{"CATCode"};
	}
	
	//print_r($arr_nhap_xuat_ton_report);
	
	//Tính nhập trong kỳ
	$num_arr_input = count($result["input"]);
	for($i =0; $i<$num_arr_input;$i++)
	{
		//Nếu đã tồn tại trong mảng nhập xuất tồn thì thêm vào nhập trong kỳ
		if(isset($arr_nhap_xuat_ton_report[$result["input"][$i]->{"AssName"}])) $arr_nhap_xuat_ton_report[$result["input"][$i]->{"AssName"}]["nhap_trong_ky"] += $result["input"][$i]->{"Quantity"};
		else //Nếu chưa tồn tại <=> tồn đầu kỳ bằng 0
		{
			$arr_nhap_xuat_ton_report[$result["input"][$i]->{"AssName"}]["ton_dau_ky"] = 0;			
			$arr_nhap_xuat_ton_report[$result["input"][$i]->{"AssName"}]["Unit"] = $result["input"][$i]->{"Unit"};
			$arr_nhap_xuat_ton_report[$result["input"][$i]->{"AssName"}]["CATCode"] = $result["input"][$i]->{"CATCode"};
			$arr_nhap_xuat_ton_report[$result["input"][$i]->{"AssName"}]["nhap_trong_ky"] = $result["input"][$i]->{"Quantity"};
			$arr_nhap_xuat_ton_report[$result["input"][$i]->{"AssName"}]["xuat_trong_ky"] = 0;
		}
	}
	
	//Tính xuất trong kỳ
	$num_arr_output = count($result["output"]);
	for($i=0;$i<$num_arr_output;$i++)
	{
		if(isset($arr_nhap_xuat_ton_report[$result["output"][$i]->{"AssName"}]))
		{
			$arr_nhap_xuat_ton_report[$result["output"][$i]->{"AssName"}]["xuat_trong_ky"] += $result["output"][$i]->{"Quantifty"};
		}
	}
	
	//Tính tồn cuối kỳ
	$num_arr_nhap_xuat_ton_report = count($arr_nhap_xuat_ton_report);
	foreach($arr_nhap_xuat_ton_report as $arr_key => $arr_value)
	{		
		$arr_nhap_xuat_ton_report[$arr_key ]["ton_cuoi_ky"] = $arr_value["ton_dau_ky"] + $arr_value["nhap_trong_ky"] - $arr_value["xuat_trong_ky"];
	}	
	
	$result["nhap_xuat_ton_report"] = $arr_nhap_xuat_ton_report;
	
	/**********KẾT THÚC ***********/
	
		
	/***********BÁO CÁO DOANH THU*******************/	
	
	
	//Lấy 100 phiếu nhập kho gần đây nhất => Giá nhập cho từng sản phẩm
	$asset_input_query = "
		SELECT AssID,AssName,CATCode,IOCode,Quantity,Unit,Price
		FROM asset_tbl 
		WHERE asset_tbl.isDeleted = 0		
		ORDER BY IOCode DESC, AssName ASC
        LIMIT 0,100
	";	
		
	$asset_input_all_arr = $oDB->stl_db_select($asset_input_query, $conn);
	
	$num_arr_ass_input = count($asset_input_all_arr);
	$arr_ass_input = "";
	
	for($i = 0; $i<$num_arr_ass_input; $i++)		
	{
		$arr_ass_input[$asset_input_all_arr[$i]->{"AssName"}]["Quantity"][] = $asset_input_all_arr[$i]->{"Quantity"};
		$arr_ass_input[$asset_input_all_arr[$i]->{"AssName"}]["Price"][] = $asset_input_all_arr[$i]->{"Price"};
		$arr_ass_input[$asset_input_all_arr[$i]->{"AssName"}]["Unit"][] = $asset_input_all_arr[$i]->{"Unit"};
	}
	
	//Lấy vị trí của đơn hàng nhập bắt đầu tính giá
		
	foreach($arr_ass_input as $assName=>$infoAss)
	{
		$tong_ton_kho =  $result["nhap_xuat_ton_report"][$assName]["xuat_trong_ky"] + $result["nhap_xuat_ton_report"][$assName]["ton_cuoi_ky"];
		
		$len = count($arr_ass_input[$assName]["Quantity"]);
		for($i = 0; $i < $len; $i++)
		{
			$tong_ton_kho = $tong_ton_kho - $arr_ass_input[$assName]["Quantity"][$i];
			if($tong_ton_kho == 0) break;
		}
		$arr_ass_input[$assName]["Vitri"] = $i;
		
	}
	
	// Tính giá theo số lượng của từng loại hàng
	$slban = "";
	$gianhap = "";
	$giaban = "";
	$IOCodeList = "";
	$CATCode = "";
	$DeliveryReceiptDate = "";
	$Unit = "";
	$assName = "";
	
	$no = 0;
	
	$ass_output_arr_tmp = $result["output"];
	for($i = 0; $i < count($ass_output_arr_tmp); $i++)
	{
		$assName = $ass_output_arr_tmp[$i]->{"AssName"};
		
		$arr_tmp_doanh_thu[$no] = "";
		
		for($j = $arr_ass_input[$assName]["Vitri"]; $j >= 0; $j--)
		{		
			$SLTam = 0;
			//Nếu số lượng nhập >0 thì mới thực hiện
			//echo $assName."---i: ".$i." -- j:".$j." if > 0 :".$arr_ass_input[$assName]["Quantity"][$j];
			if($arr_ass_input[$assName]["Quantity"][$j] > 0)
			{
				$SLTam = $ass_output_arr_tmp[$i]->{"Quantifty"} - $arr_ass_input[$assName]["Quantity"][$j];
				//echo " SLTam: ".$SLTam."<br>";
				if($SLTam >= 0)
				{
					
					$slban_tmp = $arr_ass_input[$assName]["Quantity"][$j];
					$ass_output_arr_tmp[$i]->{"Quantifty"} = $ass_output_arr_tmp[$i]->{"Quantifty"} - $arr_ass_input[$assName]["Quantity"][$j];
										
					$arr_ass_input[$assName]["Quantity"][$j] = 0;//hết hàng		
										
					$arr_tmp_doanh_thu[$no]["AssName"] = $assName;
					$arr_tmp_doanh_thu[$no]["Unit"] = $ass_output_arr_tmp[$i]->{"Unit"};	
					$arr_tmp_doanh_thu[$no]["slban"] = $slban_tmp;
					$arr_tmp_doanh_thu[$no]["giaban"] = $ass_output_arr_tmp[$i]->{"Price"};
					$arr_tmp_doanh_thu[$no]["gianhap"] = $arr_ass_input[$assName]["Price"][$j];
					$arr_tmp_doanh_thu[$no]["DeliveryReceiptDate"] = $ass_output_arr_tmp[$i]->{"DeliveryReceiptDate"};
					$arr_tmp_doanh_thu[$no]["CATCode"] = $ass_output_arr_tmp[$i]->{"CATCode"};
					$arr_tmp_doanh_thu[$no]["IOCode"] = $ass_output_arr_tmp[$i]->{"IOCode"};
					$no++;
					
				}
				else//Chuyển sang đợt nhập kế
				{
				
					$arr_ass_input[$assName]["Quantity"][$j] = $arr_ass_input[$assName]["Quantity"][$j] - $ass_output_arr_tmp[$i]->{"Quantifty"};
					
				//	$slban[$assName][] = $ass_output_arr_tmp[$i]->{"Quantifty"};
				//	$gianhap[$assName][] = $arr_ass_input[$assName]["Price"][$j];
				//	$giaban[$assName][] = $ass_output_arr_tmp[$i]->{"Price"};
					
				//	$IOCodeList[$assName][] = $ass_output_arr_tmp[$i]->{"IOCode"};
				//	$CATCode[$assName][] = $ass_output_arr_tmp[$i]->{"CATCode"};
				//	$DeliveryReceiptDate[$assName][] = $ass_output_arr_tmp[$i]->{"DeliveryReceiptDate"};
				//	$Unit[$assName][] = $ass_output_arr_tmp[$i]->{"Unit"};
					
					$arr_tmp_doanh_thu[$no]["AssName"] = $assName;
					$arr_tmp_doanh_thu[$no]["Unit"] =  $ass_output_arr_tmp[$i]->{"Unit"};
					$arr_tmp_doanh_thu[$no]["slban"] = $ass_output_arr_tmp[$i]->{"Quantifty"};
					$arr_tmp_doanh_thu[$no]["giaban"] = $ass_output_arr_tmp[$i]->{"Price"};
					$arr_tmp_doanh_thu[$no]["gianhap"] = $arr_ass_input[$assName]["Price"][$j];
					$arr_tmp_doanh_thu[$no]["DeliveryReceiptDate"] = $ass_output_arr_tmp[$i]->{"DeliveryReceiptDate"};
					$arr_tmp_doanh_thu[$no]["CATCode"] = $ass_output_arr_tmp[$i]->{"CATCode"};
					$arr_tmp_doanh_thu[$no]["IOCode"] = $ass_output_arr_tmp[$i]->{"IOCode"};
					
					$no++;
					break;
				}
				
				
			}			
		}
	}
	
	$result["doanh_thu_report"]["slban"] = $slban;
	$result["doanh_thu_report"]["gianhap"] = $gianhap;
	$result["doanh_thu_report"]["giaban"] = $giaban;
	$result["doanh_thu_report"]["IOCodeList"] = $IOCodeList;
	$result["doanh_thu_report"]["CATCode"] = $CATCode;
	$result["doanh_thu_report"]["DeliveryReceiptDate"] = $DeliveryReceiptDate;
	$result["doanh_thu_report"]["Unit"] = $Unit;	
	
	$result["doanh_thu_report_2"] = $arr_tmp_doanh_thu;	
	/***********KẾT THÚC BÁO CÁO DOANH THU**********/	
	
	$oDB->stl_closeConn($conn);
		
	echo json_encode($result);
	
?>